<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/25
 * Time: 13:51
 */

namespace app\index\controller;

use app\index\model\Coupon as Coupons;

class Coupon extends Common
{
	protected $coupons = '';
	public function _initialize()
	{
		$this->coupons = new Coupons();
		parent::_initialize();
	}
	
	/**
	 * 优惠券查询首页
	*/
	public function index()
	{
		return view('index');
	}
	
	/**
	 * 查询优惠券
	 * @param string post.coupon 优惠券
	*/
	public function queryCoupons()
	{
		if(request()->isAjax()){
			try{
				$coupon = input('post.coupon');
				$result = $this->coupons->where('name',$coupon)->find();
				if($result){
					$result['time'] = date("Y-m-d H:i:s",$result['time']);
					throw new \PDOException($result);
				}
				$success = ['success'=>'可用'];
				return json($success);
			}catch (\PDOException $e){
				$error = ['error'=>$e->getMessage()];
				return json($error);
			}
		}
	}
	
	/**
	 * 添加优惠券
	 * @param string post.coupon 优惠券
	*/
	public function insert()
	{
		try{
			$input['name'] = input('post.coupon');
			$input['time'] = time();
			$id = $this->coupons->insertGetId($input);
			if(!$id){
				throw new \PDOException('添加失败');
			}
			$success = ['success'=>'添加成功'];
			return json($success);
		}catch (\PDOException $e){
			$error = ['error'=>$e->getMessage()];
			return json($error);
		}
	}
	
	/**
	 * 统计当天的优惠券使用次数
	*/
	public function total()
	{
		$time = date('Y-m-d',time());
		$date = explode('-',date('Y-m-d H:i:s',time()));
		$data = getStartAndEndUnixTimestamp($date[0],$date[1],$date[2]);
		$total = $this->coupons->where('time','>',$data['start'])->where('time','<',$data['end'])->count();
		return view('total',compact('total','time'));
	}
}